package com.zpark.merchant.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zpark.jushanpay.common.domain.BusinessException;
import com.zpark.jushanpay.common.domain.CommonErrorCode;
import com.zpark.jushanpay.common.domain.PageVO;
import com.zpark.jushanpay.common.domain.RestResponse;
import com.zpark.jushanpay.common.util.*;
import com.zpark.merchant.api.dto.MerchantDTO;
import com.zpark.merchant.api.dto.StoreDTO;
import com.zpark.merchant.api.service.IAppService;
import com.zpark.merchant.api.service.IFileService;
import com.zpark.merchant.api.service.ISmsService;
import com.zpark.merchant.app.convert.MerchantRegisterConvert;
import com.zpark.merchant.app.feign.ITransactionPayChannelFeign;
import com.zpark.merchant.app.vo.MerchantDetailVO;
import com.zpark.merchant.app.vo.MerchantRegisterVO;
import com.zpark.merchant.service.entity.Merchant;
import com.zpark.merchant.api.service.IMerchantService;
import com.zpark.transaction.api.dto.QRCodeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 商户控制层，负责对外提供服务（给前端提供访问接口）
 */
@RestController
@RequestMapping("/merchant-app")
public class MerchantAppController {

    // 自动注入业务层接口
    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private ISmsService smsService;

    @Autowired
    private IFileService fileService;

    @Autowired
    private ITransactionPayChannelFeign transactionPayChannelFeign;

    @Autowired
    private IAppService appService;


    /**
     * 门店二维码订单标题
     */
    @Value("${shanjupay.c2b.subject}")
    private String subject;
    /**
     * 门店二维码订单内容
     */
    @Value("${shanjupay.c2b.body}")
    private String body;



    /**
     * 获取验证码
     * @param phone 手机号
     * @return
     */
    @GetMapping("/sms")
    public RestResponse<String> getSMSCode(String phone){
        // 调用业务层发送短信
        String smsKey = smsService.sendMsg(phone);
        return RestResponse.success(smsKey);
    }

    /**
     * 商户注册接口
     * @param vo 商户注册对象
     * @return
     */
    @PostMapping("/reg")
    public RestResponse<MerchantRegisterVO> registerMerchant(@RequestBody MerchantRegisterVO vo){
        // 1、判断vo是否未null
        if (vo == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }
        // 校验手机号是否为空
        if (vo.getMobile() == null) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        // 校验手机号是否满足要求
        if (!PhoneUtil.isMatches(vo.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }
        // 校验是否有联系人姓名
        if (StringUtil.isBlank(vo.getUsername())) {
            throw new BusinessException(CommonErrorCode.E_100110);
        }
        // 校验密码是否为空
        if (StringUtil.isBlank(vo.getPassword())) {
            throw new BusinessException(CommonErrorCode.E_100111);
        }

        // 校验验证码是否为空
        if (StringUtil.isBlank(vo.getVerifyCode())
        || StringUtil.isBlank(vo.getVerifyKey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }

        // 2、校验验证码
        smsService.checkVerifyCode(vo.getVerifyCode(), vo.getVerifyKey());

        // 将vo转为dto
        MerchantDTO dto = MerchantRegisterConvert.INSTANCE.merVoToMerDto(vo);

        // 3、调用业务层进行商户注册
        MerchantDTO merchantDTO = merchantService.createMerchant(dto);

        // 将Dto转为vo
        vo = MerchantRegisterConvert.INSTANCE.merDtoToMerVo(merchantDTO);

        return RestResponse.success(vo);
    }


    /**
     * 文件上传接口
     * @param file 文件对象
     * @return 文件的访问url
     */
    @PostMapping("/upload")
    public RestResponse<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 获取文件的名字
        String filename = file.getOriginalFilename();
        // 获取文件的后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        // 生成文件名字
        String newFileName = UUID.randomUUID().toString() + suffix;
        // 调用业务层代码上传文件
        String fileUrl = fileService.upload(file.getBytes(), newFileName);
        return RestResponse.success(fileUrl);
    }


    // 商户资质申请接口
    @PostMapping("/save_merchant")
    public RestResponse<Void> saveMerchant(@RequestBody MerchantDetailVO vo){
        // 判断vo是否为null
        if (vo ==null) {
            throw new BusinessException(CommonErrorCode.E_200201);
        }
        // 从token当中解析商户的id
        Long merchantId = SecurityUtil.getMerchantId();
        // 将vo转为dto
        MerchantDTO dto = MerchantRegisterConvert.INSTANCE.merDetVoToMerDto(vo);
        // 调用业务层接口实现资质申请
        merchantService.applyMerchant(merchantId, dto);

        return RestResponse.success(null);
    }


    /**
     * 创建门店二维码
     * @param storeId
     * @param appId
     * @return
     * @throws IOException
     */
    @PostMapping("/app_store_qrcode/apps/{appId}/stores/{storeId}")
    public RestResponse<String> createStoreQRCode(
            @PathVariable("appId") String appId,
            @PathVariable("storeId") String storeId) throws IOException {
        // 获取商户id
        Long merchantId = SecurityUtil.getMerchantId();

        // 调用校验商户id与应用appid方法
        // 判断结果，如果为false，则抛出异常
        if (!appService.queryAppInMerchant(appId, merchantId)) {
            // 不合法，抛出异常
            throw new BusinessException(CommonErrorCode.E_200022);
        }
        // 调用商户id与门店id是否合法方法
        // 判断结果，如果为false，则抛出异常
        if (!merchantService.queryStoreIdInMerchantId(Long.parseLong(storeId), merchantId)) {
            // 不合法，抛出异常
            throw new BusinessException(CommonErrorCode.E_200023);
        }

        // 根据商户id查询商户数据
        MerchantDTO merchantDTO = merchantService.findById(merchantId);

        // 创建二维码信息bean
        QRCodeDTO dto = new QRCodeDTO();

        // 设置商户id
        dto.setMerchantId(merchantId);
        // 设置门店id
        dto.setStoreId(Long.parseLong(storeId));
        // 设置应用id
        dto.setAppId(appId);
        // 设置订单标题
        dto.setSubject(String.format(subject, merchantDTO.getMerchantName()));
        // 设置订单描述信息body
        dto.setBody(String.format(body, merchantDTO.getMerchantName()));

        // 通过feign接口调用订单服务创建二维码
        RestResponse<String> storeQRCode = transactionPayChannelFeign.createStoreQRCode(dto);
        // 获取二维码信息
        String url = storeQRCode.getResult();

        return RestResponse.success(QRCodeUtil.createQRCode(url, 300, 300));
    }







    @GetMapping("/get_token")
    public String getTokenTest(){
        Long merchantId = 1795669081328742401L;//填写用于测试的商户id
        MerchantDTO merchantDTO = merchantService.findById(merchantId);
        JSONObject token = new JSONObject();
        token.put("mobile", merchantDTO.getMobile());
        token.put("user_name", merchantDTO.getUsername());
        token.put("merchantId", merchantId);

        String jwt_token = "Bearer " + EncryptUtil.encodeBase64(JSON.toJSONString(token).getBytes());
        System.out.println(jwt_token);

        return jwt_token;
    }
}
